package com.it.water.controller.ImageController;

import com.it.water.Dao.MessageRepository;
import com.it.water.entity.DataEntity.MessageEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 接受图片消息
 */
@RestController
public class MessageController {

    @Autowired
    private MessageRepository messageRepository;

    @PostMapping("/receive-message-and-image")
    public String receiveMessageAndImage(@RequestParam("message") String messageContent,
                                         @RequestParam("file") MultipartFile file) {
        try {
            //保存图片到服务器
            String imagePath = "C:\\Users\\86139\\Desktop\\demo\\" + file.getOriginalFilename();
            file.transferTo(new File(imagePath));

            // 创建一个消息实体
            MessageEntity messageEntity = new MessageEntity();
//            messageEntity.setId();
            messageEntity.setMessageContent(messageContent);
           messageEntity.setImagePath(imagePath);
//           messageEntity.setImage(String.valueOf(file));

            // 将消息实体保存到数据库
            messageRepository.save(messageEntity);

            return "Message and image saved successfully";
        } catch (Exception e) {
            e.printStackTrace();
            return "Error occurred while saving message and image";
        }
    }
}
